<script setup>
import useCategoruStore from '@/store/modules/category'
import { watch } from 'vue'
import { getAttrInfoAPI, addOrUpdateAttrAPI, deleteAttrAPI } from '@/api/product/attr'
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { nextTick } from 'vue'
import { onBeforeUnmount } from 'vue'

const categoryStore = useCategoruStore()

// 表单数据
const attrArr = ref([])

// 修改与添加属性界面的显示控制变量
const editShowFlag = ref(0)

// 收集新增属性的数据
let attrParams = ref({
  attrName: '', // 新增的属性名
  attrValueList: [], // 新增的属性值数组
  CategoryId: '', // 三级分类的id
  CategoryLevel: 3 // 表明为三级分类
})

watch(
  () => categoryStore.c3Id,
  () => {
    attrArr.value = []
    if (!categoryStore.c3Id) {
      return
    }
    getAttrInfo()
  },
)

const getAttrInfo = async () => {
  const { c1Id, c2Id, c3Id } = categoryStore
  let res = await getAttrInfoAPI(c1Id, c2Id, c3Id)
  if (res.code === 200) {
    attrArr.value = res.data
  }
}

// 添加属性
const addAttr = () => {
  // 每一次点击时，先清空再收集数据
  Object.assign(attrParams.value, {
    attrName: '', // 新增的属性名
    attrValueList: [], // 新增的属性值数组
    CategoryId: categoryStore.c3Id, // 三级分类的id,改为在这里收集三级id
    CategoryLevel: 3 // 表明为三级分类
  })
  // 点击按钮收集三级id
  // attrParams.value.CategoryId = categoryStore.c3Id
  // 切换为添加与修改的界面
  editShowFlag.value = 1
}

// 编辑属性
const updateAttr = (row) => {
  editShowFlag.value = 1
  Object.assign(attrParams.value, JSON.parse(JSON.stringify(row)))
}

const cancel = () => {
  editShowFlag.value = 0
}

// 添加属性值
const addAttrValue = () => {
  // 点击添加属性值按钮时，向数组添加一个属性值对象
  attrParams.value.attrValueList.push({
    valueName: '',
    flag: true
  })
  // 新增项自动聚焦
  nextTick(() => {
    inputArr.value[attrParams.value.attrValueList.length - 1].focus()
  })
}

// 保存属性值
const save = async () => {
  let res = await addOrUpdateAttrAPI(attrParams.value)
  if(res.code === 200) {
    // 切换场景
    editShowFlag.value = 0
    ElMessage({
      type: 'success',
      message: attrParams.value.id ? '修改成功' : '添加成功'
    })
    // 添加成功后再获取一次所有的属性值
    getAttrInfo()
  } else {
    ElMessage({
      type: 'error',
      message: attrParams.value.id ? '修改失败' : '添加失败'
    })
  }
}

// 属性值转为查看模式
const toLook = (row, $index) => {
  // 非法情况1，内容为空
  if(!row.valueName.trim()) {
    // 删除属性值为空的元素
    attrParams.value.attrValueList.splice($index, 1)
    ElMessage({
      type: 'error',
      message: '属性值不能为空'
    })
    return
  }
  // 非法情况2，属性名重复
  let repeat = attrParams.value.attrValueList.find(item => {
    // 选择和当前对象不相等的对象，再判断两者的属性名是否相等，最后返回一个布尔值
    if(item !== row) {
      return item.valueName === row.valueName
    }
  })
  if (repeat) {
    // 删除重复的元素
    attrParams.value.attrValueList.splice($index, 1)
    ElMessage({
      type: 'error',
      message: '属性值不能重复'
    })
    return
  }
  row.flag = false
}

// 属性值转为编辑模式
const toEdit = (row, index) => {
  row.flag = true
  nextTick(() => {
    inputArr.value[index].focus()
  })
}

// 获取属性值表单对象
const inputArr = ref([])

// 删除属性函数
const deleteAttr = async (attrId) => {
  let res = await deleteAttrAPI(attrId)
  if(res.code === 200) {
    ElMessage({
      type: 'success',
      message: '删除成功'
    })
    getAttrInfo()
  } else {
    ElMessage({
      type: 'error',
      message: '删除失败'
    })
  }
}

// 在组件销毁前清除仓库的内容，包括分类数据等
onBeforeUnmount(() => {
  // 清空仓库的数据
  categoryStore.c1Arr = []
  categoryStore.c2Arr = []
  categoryStore.c3Arr = []
  categoryStore.c1Id = null
  categoryStore.c2Id = null
  categoryStore.c3Id = null
})
</script>

<template>
  <div>
    <Category :disableFlag="editShowFlag"></Category>
    <el-card style="margin: 10px 0">
      <div v-show="editShowFlag === 0">
        <el-button type="primary" icon="Plus" :disabled="!categoryStore.c3Id" @click="addAttr">
          添加平台属性
        </el-button>

        <el-table border style="margin: 10px 0" :data="attrArr">
          <el-table-column
            label="序号"
            type="index"
            width="80px"
            align="center"
          ></el-table-column>
          <el-table-column
            label="属性名称"
            width="260px"
            prop="attrName"
          ></el-table-column>
          <el-table-column label="属性值名称">
            <template #default="{ row }">
              <el-tag
                style="margin: 5px"
                v-for="item in row.attrValueList"
                :key="item.id"
                type="primary"
                size="default"
              >
                {{ item.valueName }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="260px">
            <template #default="{row, $index}">
              <el-button type="primary" size="default" icon="Edit" @click="updateAttr(row, $index)"></el-button>
              <el-popconfirm
              title="确定要删除该属性吗？"
              icon="Delete"
              @confirm="deleteAttr(row.id)">
                <template #reference>
                  <el-button
                    type="primary"
                    size="default"
                    icon="Delete"
                  >
                  </el-button>
                </template>
              </el-popconfirm>
              
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div v-show="editShowFlag === 1">
        <el-form :inline="true">
          <el-form-item label="属性名称" size="default">
            <el-input placeholder="请您输入属性名称" v-model="attrParams.attrName"/>
          </el-form-item>
        </el-form>
        <el-button type="primary" size="default" icon="Plus" @click="addAttrValue" :disabled="!attrParams.attrName.trim()">添加属性值</el-button>
        <el-button size="default" @click="cancel">取消</el-button>
        <el-table border style="margin: 10px 0" :data="attrParams.attrValueList">
          <el-table-column
          label="序号" width="80px" align="center" type="index">
          </el-table-column>
          <el-table-column
          label="属性值">
            <template #default="{row, $index}">
              <!-- 通过ref获取新建的input对象，ref触发的时机是对象发生改变时(如创建、修改等) -->
              <el-input :ref="(el) => inputArr[$index] = el" v-if="row.flag" @blur="toLook(row, $index)" v-model="row.valueName" placeholder="请输入属性值名称"/>
              <div v-else @click="toEdit(row, $index)">{{ row.valueName }}</div>
            </template>
          </el-table-column>
          <el-table-column
          label="操作">
            <template #default="{$index}">
              <el-button type="danger" icon="Delete" @click="attrParams.attrValueList.splice($index, 1)"></el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-button type="primary" size="default" @click="save" :disabled="attrParams.attrValueList.length > 0 ? false : true">保存</el-button>
        <el-button size="default" @click="cancel">取消</el-button>
        
      </div>
    </el-card>
  </div>
</template>

<style scoped></style>
